package com.jp.knowledge.my.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.quicksidebar.QuickSideBarTipsView;
import com.bigkoo.quicksidebar.QuickSideBarView;
import com.bigkoo.quicksidebar.listener.OnQuickSideBarTouchListener;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.jiayen.dialog.LoadingDialog;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.comm.JpApplication;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.adapter.ColleagueContactsAdapter;
import com.jp.knowledge.my.model.ColleagueContactsModel;
import com.jp.knowledge.my.model.OrganizaModel;
import com.jp.knowledge.my.util.ContactUtil;
import com.jp.knowledge.my.util.MyUtil;
import com.jp.knowledge.my.util.PinyinComparator;
import com.jp.knowledge.util.ResultSubscriber;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import pl.droidsonroids.gif.GifImageView;


/**
 * Created by 528787067@qq.com on 2017/4/14.
 */

public class InviteMemberFragment extends Fragment implements ResultSubscriber.OnResultListener {

    private static int GET_CONTACTS_CODE = 0x01;
    private static int INVITE_MEMBER_CODE = 0x02;

    private Context mContext;
    private OrganizaModel organizaModel;
    private List<String> letters;

    private List<ContactUtil.ContactModel> contactModels;   // 代表读取手机里面的通讯录
    private List<ColleagueContactsModel> allContacts;       // 代表全部的通讯录
    private List<ColleagueContactsModel> showContacts;      // 代表用于展示的通讯录
    private ColleagueContactsAdapter adapter;
    private LinearLayoutManager layoutManager;

    private View contentView;
    private EditText searchInput;
    private ImageView clearEditBtn;
    private RecyclerView mainContentView;
    private QuickSideBarTipsView quickSideBarTipsView;
    private QuickSideBarView quickSideBarView;
    private LoadingDialog loadingDialog;
    private GifImageView loadView;

    public static InviteMemberFragment newInstance(OrganizaModel company){
        InviteMemberFragment fragment = new InviteMemberFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("company", company);
        fragment.setArguments(bundle);
        return fragment;
    }

    public String getCompanyId(){
        if(organizaModel != null)
            return organizaModel.getCompanyId();
        return null;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(mContext == null){
            mContext = getContext();
            organizaModel = (OrganizaModel) getArguments().getSerializable("company");

            allContacts = new ArrayList<>();
            showContacts = new ArrayList<>();
            loadingDialog = new LoadingDialog(mContext);
            adapter = new ColleagueContactsAdapter(mContext, new ArrayList<ColleagueContactsModel>());
            adapter.setInviteLister(new ColleagueContactsAdapter.InviteLister() {
                @Override
                public void invite(ColleagueContactsModel personMode) {
//                    loadingDialog.show();
                    JsonObject param = new JsonObject();
                    param.addProperty("phone", personMode.getPhone());
                    if(organizaModel.getCompanyType() == 2)
                        param.addProperty("id", organizaModel.getClassId());
                    else
                        param.addProperty("id", organizaModel.getCompanyId());
                    param.addProperty("type", organizaModel.getCompanyType());
                    int position = showContacts.indexOf(personMode);
//                    HttpHelper.getInstance(mContext).invitation(param, position*10+INVITE_MEMBER_CODE, InviteMemberFragment.this);

                    String smsContent = "%s<%s>，邀请你加入团队。马上点击以下链接http://team580.com/%s，下载app后通过手机验证码登录，团队成员都在等你了，点击链接快快加入哦！";
                    try {
                        UserData userData = ((JpApplication)getActivity().getApplication()).getUserData();
                        smsContent = String.format(smsContent, userData.getUsername(), organizaModel.getCompanyName(), "");
                    } catch (Exception e){
                        smsContent = "";
                    } finally {
                        Uri smsToUri = Uri.parse("smsto:" + personMode.getPhone());
                        Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
                        intent.putExtra("sms_body", smsContent);
                        startActivity(intent);
                    }
                }
            });

            contentView = View.inflate(mContext, R.layout.fragment_constacts, null);
            contentView.findViewById(R.id.bottom_bar).setVisibility(View.GONE);
            searchInput = (EditText) contentView.findViewById(R.id.team_circle_contacts_edit_search);
            clearEditBtn = (ImageView) contentView.findViewById(R.id.team_circle_contacts_iv_clear);
            mainContentView = (RecyclerView) contentView.findViewById(R.id.team_circle_contacts_rv);
            quickSideBarTipsView = (QuickSideBarTipsView) contentView.findViewById(R.id.team_circle_contacts_btv);
            quickSideBarView = (QuickSideBarView) contentView.findViewById(R.id.team_circle_contacts_sbv);
            loadView = (GifImageView) contentView.findViewById(R.id.loading_bg);

            layoutManager = new LinearLayoutManager(mContext);
            mainContentView.setLayoutManager(layoutManager);
            mainContentView.setHasFixedSize(true);
            // 添加粘性头部视图
            StickyRecyclerHeadersDecoration headersDecor =
                    new StickyRecyclerHeadersDecoration(adapter);
            mainContentView.addItemDecoration(headersDecor);
            mainContentView.setAdapter(adapter);
            mainContentView.setOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    MyUtil.closeKeyword(mContext, searchInput);
                    if (movePosition < 0)
                        return;
                    int n = movePosition - layoutManager.findFirstVisibleItemPosition();
                    if (0 <= n && n < mainContentView.getChildCount()){
                        int top = mainContentView.getChildAt(n).getTop();
                        mainContentView.scrollBy(0, top);
                    }
                    movePosition = -1;
                }
            });

            letters = Arrays.asList(getResources().getStringArray(R.array.constacts_letters));
            quickSideBarView.setLetters(letters);
            quickSideBarView.setOnQuickSideBarTouchListener(new OnQuickSideBarTouchListener() {
                @Override
                public void onLetterChanged(String letter, int position, float y) {
                    MyUtil.closeKeyword(mContext, searchInput);
                    quickSideBarTipsView.setText(letter, position, (quickSideBarView.getY() - quickSideBarTipsView.getY()) + y - quickSideBarTipsView.getWidth());
                    letterChanged(letter, position, y);
                }
                @Override
                public void onLetterTouching(boolean touching) {
                    quickSideBarTipsView.setVisibility(touching ? View.VISIBLE : View.INVISIBLE);
                }
            });

            clearEditBtn.setVisibility(View.GONE);
            clearEditBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    searchInput.setText("");
                }
            });
            searchInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (actionId == EditorInfo.IME_ACTION_DONE) {
                        MyUtil.closeKeyword(mContext, searchInput);
                    }
                    return true;
                }
            });
            searchInput.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {}
                @Override
                public void afterTextChanged(Editable s) {
                    if(s.length() == 0 && clearEditBtn.getVisibility() != View.GONE)
                        clearEditBtn.setVisibility(View.GONE);
                    else if(s.length() != 0 && clearEditBtn.getVisibility() != View.VISIBLE)
                        clearEditBtn.setVisibility(View.VISIBLE);
                    editTextChange();
                }
            });
            getData();
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return contentView;
    }

    private void letterChanged(String letter, int position, float y){
        for(int i = 0; i < showContacts.size(); i++){
            if(showContacts.get(i).getRemark().charAt(0) == letters.get(position).charAt(0)){
                moveToPosition(i);
                return;
            }
        }
    }

    private int movePosition = -1;
    private void moveToPosition(int position) {
        int firstItem = layoutManager.findFirstVisibleItemPosition();
        int lastItem = layoutManager.findLastVisibleItemPosition();
        if (position <= firstItem){
            mainContentView.scrollToPosition(position);
        }else if (position <= lastItem){
            int top = mainContentView.getChildAt(position - firstItem).getTop();
            mainContentView.scrollBy(0, top);
        }else{
            mainContentView.scrollToPosition(position);
            movePosition = position;
        }
    }

    private void editTextChange(){
        String searchStr = searchInput.getText().toString().trim();
        showContacts.clear();
        if(searchStr.length() == 0){
            showContacts.addAll(allContacts);
        } else{
            for(ColleagueContactsModel model : allContacts){
                if(model.getName().contains(searchStr) || model.getPhone().contains(searchStr))
                    showContacts.add(model);
            }
        }
        adapter.updateAdapter(showContacts);
    }

    private void getData(){
        contactModels = ContactUtil.getContactUtil().getContactInfo(mContext);
        // 使用 set 去除重复号码
        Set<String> phoneNumbers = new HashSet<>();
        for(int i = 0; i < contactModels.size(); i++){
            if(contactModels.get(i).getPhoneModels() == null)
                continue;
            for(int j = 0; j < contactModels.get(i).getPhoneModels().size(); j++) {
                phoneNumbers.add(contactModels.get(i).getPhoneModels().get(j).getPhoneNumber().replaceAll("-", ""));
            }
        }
        if(phoneNumbers.size() == 0)
            return;
        List<String> phoneList = new ArrayList<>(phoneNumbers);
        JsonObject param = new JsonObject();
        JsonArray jsonArray = new Gson().toJsonTree(phoneList, new TypeToken<List<String>>() {}.getType()).getAsJsonArray();
        param.add("phones", jsonArray);
        param.addProperty("companyId", organizaModel.getCompanyId());
        HttpHelper.getInstance(mContext).phonebook(param, GET_CONTACTS_CODE, this);
    }

    @Override
    public void onStart(int requestType) {
        if(requestType == GET_CONTACTS_CODE){
            loadView.setVisibility(View.VISIBLE);
            mainContentView.setVisibility(View.GONE);
            quickSideBarTipsView.setVisibility(View.GONE);
            quickSideBarView.setVisibility(View.GONE);
        }
    }
    @Override
    public void onCompleted(int requestType) {
        if(requestType == GET_CONTACTS_CODE){
            loadView.setVisibility(View.GONE);
            mainContentView.setVisibility(View.VISIBLE);
            quickSideBarTipsView.setVisibility(View.VISIBLE);
            quickSideBarView.setVisibility(View.VISIBLE);
        } else if(requestType%10 == INVITE_MEMBER_CODE){
            loadingDialog.cancel();
        }
    }
    @Override
    public void onError(int requestType) {
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            ToasUtil.toast(mContext, data.getMessage());
            onError(requestType);
        } else if(requestType == GET_CONTACTS_CODE){
            allContacts = data.getList(ColleagueContactsModel.class);
            if(allContacts != null) {
                for (ColleagueContactsModel model : allContacts) {
                    if(model == null)
                        continue;
                    if (model.getName() == null || model.getName().trim().length() == 0) {
                        for (ContactUtil.ContactModel contactModel : contactModels) {
                            try {
                                if(model.getPhone().equals(contactModel.getPhoneModels().get(0).getPhoneNumber())) {
                                    model.setName(contactModel.getNameModels().get(0).getDisplayName());
                                    break;
                                }
                            } catch (Exception e){}
                        }
                        if (model.getName() == null || model.getName().trim().length() == 0)
                            model.setName(model.getPhone());
                    }
                    String remark = model.getName();
                    remark = PinyinComparator.getPinyin(remark).toUpperCase();
                    if (!(remark.charAt(0) >= 'A' && remark.charAt(0) <= 'Z'))
                        remark = '#' + remark;
                    model.setRemark(remark);
                }
            }
            showContacts.clear();
            showContacts.addAll(allContacts);
            adapter.updateAdapter(showContacts);
        } else if(requestType%10 == INVITE_MEMBER_CODE){
            ToasUtil.toast(mContext, "你的邀请已经发出，请耐心等待对方的回复");
        }
    }
}
